<template>
  <div class="upload-component">
    <div class="upload-input">
      <input @change="handleFileChange" :ref="`Uploader-${uploadId}`" :id="uploadId" class="vision-hide" type="file" :accept="accept" />
      <el-button :loading="uploading" @click="handleUploadFile" type="primary" plain size="small">{{ btnName }}</el-button>
      <div class="tips" v-show="tipsText">
        <span class="color-danger text-bold">温馨提示：</span>
        {{ tipsText }}
      </div>
    </div>
    <upload-preview :file-list="fileList" @remove-file="removeFile" :show-del="true" v-if="fileList.length"></upload-preview>
  </div>
</template>

<script>
import * as fileApi from "@/api/file";
import uploadPreview from "./uploadPreview";
import { fileSize } from "@/utils/common";
export default {
  name: "UploadInput",
  components: {
    uploadPreview,
  },
  props: {
    accept: {
      type: String,
      default: ".bmp,.jpg,.jpeg,.png,.tif,.gif,.mov,.avi,.mp4,.wmv,.rmvb,.docx,.pptx,.xlsx,.doc,.ppt,.xls,.pdf,.rar,.zip,.7z",
    },
    tipsText: {
      type: String,
      default: "请按照填报要求提供与投诉举报事项相关的资料，上传的附件大小不能超过100M，附件类型支持图片，视频，文档，压缩包等格式文件。",
    },
    btnName: {
      type: String,
      default: "上传附件",
    },
    size: {
      type: Number,
      default: 100,
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    limitNum: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),
      uploading: false,
    };
  },
  watch: {
    fileList: {
      handler(news) {
        this.$emit("update:fileList", this.fileList);
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {
    handleUploadFile() {
      this.$refs[`Uploader-${this.uploadId}`].click();
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (fileSize(file) > this.size) {
        this.clearFileInput();
        return this.$message.error(`请上传${this.size}M以内的文件`);
      }

      if (!this.limitNum || (this.limitNum && this.fileList.length < this.limitNum)) {
        const formData = new FormData();
        formData.append("file", file);
        this.uploading = true;
        fileApi
          .upload(formData)
          .then((res) => {
            this.$message.success("上传成功");
            this.fileList.push({
              fileName: file.name,
              fileUrl: res.data,
            });
          })
          .finally(() => {
            this.clearFileInput();
            this.uploading = false;
            this.$emit("change", this.fileList);
          });
      } else {
        this.$message.error(`最多上传${this.limitNum}个文件`);
      }
    },
    clearFileInput() {
      document.getElementById(this.uploadId).value = "";
    },
    removeFile(index) {
      this.fileList.splice(index, 1);
    },
  },
};
</script>
<style lang="less" scoped>
.upload-input {
  display: flex;
  align-items: center;
}
.tips {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
  text-align: left;
  line-height: 20px;
}
.color-danger {
  list-style-type: none;
  font-size: 14px;
}
.el-button {
  font-weight: 600;
  font-size: 16px;
}
</style>
